<!--  -->
<script setup>
import { ref } from "vue";
import { NInputNumber } from "naive-ui";
import { bwPowerSet } from "@/utils";
import { selectLight } from "naive-ui/lib/select/styles";

const emit = defineEmits(["change"]);

const props = defineProps({
  goods: {
    type: Object,
    default: {},
  },
  skuId: {
    type: String,
    default: "",
  },
});

// 初始化默认选中
const initDefaultSelected = (goods, skuId) => {
  const sku = goods.skus.find((item) => item.id === skuId);
  // 选择完整sku组合按钮
  emit("change", {
    skuId: sku.id,
    price: sku.price,
    oldPrice: sku.oldPrice,
    inventory: sku.inventory,
    spacsText: sku.specs
      .reduce((p, c) => `${p} ${c.name}: ${c.valueName}`, "")
      .trim(),
  });
  goods.specs.forEach((item, i) => {
    const val = item.values.find((val) => val.name === sku.specs[i].valueName);
    val.selected = true;
  });
};
if (props.skuId) {
  initDefaultSelected(props.goods, props.skuId);
}
// 获取当前选择的项
const getSelectedValues = (specs) => {
  const arr = [];
  // 循环specs
  specs.forEach((el) => {
    // 获取当前选择的项
    const selectedVal = el.values.find((val) => val.selected);
    // push 到arr 并返回
    arr.push(selectedVal ? selectedVal.name : undefined);
  });
  return arr;
};

// 更新按钮禁用
const updateDisabledStatus = (specs, pathMap) => {
  /**
   * 循环规格
   * element 当前项
   * i 当前项 key 值
   */
  specs.forEach((element, i) => {
    // 获取当前选择的项
    const SelectedValues = getSelectedValues(specs);
    // 循环规格下的种类
    element.values.forEach((el) => {
      // 如果当前种类被选中则直接返回
      if (el.selected) return;
      // 否则将当前种类名字加到SelectedValues中的某一项中
      SelectedValues[i] = el.name;
      // 过滤 undefined 并用 ★ 链接数组
      const key = SelectedValues.filter((item) => item).join("★");
      // 种类的 disabled 属性 等于 路径地图中的key项
      el.disabled = !pathMap[key];
    });
  });
};

const getPathMap = (skus) => {
  const pathMap = {};
  // 1. 拿到所有sku集合  props.goods.skus
  // 2. 筛选有效sku
  skus.forEach((sku) => {
    if (sku.inventory > 0) {
      // 计算当前有库存的sku的子级
      // 例如 【1,2】 => [1] [2] [1,2]
      // 可选值数组
      const valueArr = sku.specs.map((val) => val.valueName);
      // 可选值数组 子级
      // 3. 根据有效sku使用bwPowerSet 得到子级
      const valueArrPowerSet = bwPowerSet(valueArr);
      // 4. 根据子级向字典对象中存储key value
      valueArrPowerSet.forEach((arr) => {
        const key = arr.join("★");
        if (pathMap[key]) {
          pathMap[key].push(sku.id);
        } else {
          pathMap[key] = [sku.id];
        }
      });
    }
  });
  return pathMap;
};

const pathMap = getPathMap(props.goods.skus);

updateDisabledStatus(props.goods.specs, pathMap);

let specsKey = ref("");

const changeSku = (item, val) => {
  if (val.disabled) return;

  if (val.selected) {
    val.selected = false;
  } else {
    item.values.forEach((element) => {
      element.selected = false;
    });
    val.selected = true;
  }
  updateDisabledStatus(props.goods.specs, pathMap);
  const selectedVal = getSelectedValues(props.goods.specs).filter((v) => v);
  if (selectedVal.length === props.goods.specs.length) {
    const skuIds = pathMap[selectedVal.join("★")];
    const sku = props.goods.skus.find((item) => item.id === skuIds[0]);

    // 选择完整sku组合按钮
    emit("change", {
      skuId: sku.id,
      price: sku.price,
      oldPrice: sku.oldPrice,
      inventory: sku.inventory,
      spacsText: sku.specs
        .reduce((p, c) => `${p} ${c.name}: ${c.valueName}`, "")
        .trim(),
    });
  } else {
    // 选择不完整sku组合按钮
    emit("change", {});
  }
};
</script>

<template>
  <div class="goods-sku">
    <dl v-for="item in goods.specs" :key="item.id">
      <dt>{{ item.name }}</dt>
      <dd>
        <template v-for="val in item.values" :key="val.name">
          <img
            v-if="val.picture"
            :class="{ selected: val.selected, disabled: val.disabled }"
            :src="val.picture"
            :title="val.name"
            @click="changeSku(item, val)"
          />
          <span
            v-else
            @click="changeSku(item, val)"
            :class="{ selected: val.selected, disabled: val.disabled }"
            >{{ val.name }}</span
          >
        </template>
      </dd>
    </dl>
  </div>
</template>

<style lang='less' scoped>
.sku-state-mixin () {
  border: 1px solid #e4e4e4;
  margin-right: 10px;
  cursor: pointer;
  &.selected {
    border-color: @xtxColor;
  }
  &.disabled {
    opacity: 0.6;
    border-style: dashed;
    cursor: not-allowed;
  }
}
.goods-sku {
  user-select: none;
  padding-left: 20px;
  padding-top: 20px;
  dl {
    display: flex;
    padding-bottom: 20px;
    align-items: center;
    dt {
      width: 50px;
      color: #999;
    }
    dd {
      flex: 1;
      color: #666;
      > img {
        width: 50px;
        height: 50px;
        .sku-state-mixin ();
      }
      > span {
        display: inline-block;
        height: 30px;
        line-height: 28px;
        margin: 2px 0px;
        padding: 0 20px;
        .sku-state-mixin ();
      }
    }
  }
}
</style>